package com.example.state.machine.service.impl;

import com.example.state.machine.entity.Payment;
import com.example.state.machine.enums.PaymentEvent;
import com.example.state.machine.enums.PaymentState;
import com.example.state.machine.service.PaymentService;
import jakarta.annotation.Resource;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private StateMachineFactory<PaymentState, PaymentEvent> stateMachineFactory;

//    @Resource
//    private PaymentRepository paymentRepository;

    // 创建支付记录（初始状态为INITIALIZED）
    public Payment createPayment(BigDecimal amount) {
        Payment payment = new Payment();
        payment.setAmount(amount);
        payment.setState(PaymentState.INITIALIZED);
        return paymentRepository.save(payment);
    }

    // 调用第三方支付网关
    public void processPayment(Long paymentId) {
        StateMachine<PaymentState, PaymentEvent> stateMachine = stateMachineFactory.getStateMachine(paymentId.toString());
        stateMachine.start();

        try {
            // 触发支付开始事件
            stateMachine.sendEvent(PaymentEvent.START_PAY);

            // 模拟调用支付网关
            boolean success = callPaymentGateway();

            // 根据结果触发成功或失败事件
            if (success) {
                stateMachine.sendEvent(PaymentEvent.PAY_SUCCESS);
            } else {
                stateMachine.sendEvent(PaymentEvent.PAY_FAIL);
            }

            // 持久化状态
            Payment payment = paymentRepository.findById(paymentId).orElseThrow();
            payment.setState(stateMachine.getState().getId());
            paymentRepository.save(payment);
        } finally {
            stateMachine.stop();
        }
    }


    private boolean callPaymentGateway() {
        // 实际调用支付接口的逻辑
        return Math.random() > 0.5;  // 模拟50%成功率
    }

}
